﻿using System;
using FFIV.Lib.BusinessRules;
using FFIV.Lib.DataComponent;
using FFIV.Lib.IView.Articles;
using FFIV.Lib.Model;
using FFIV.Lib.Utilities;

namespace FFIV.Lib.Controlers.Articles
{
	public class DetailController
	{
		private readonly IArticleDetails m_Detail;
		private readonly IArticlesMiniList m_MiniList;

		private HtmlHeaderInfo m_HtmlHeader;

		public DetailController(IArticleDetails View, IArticlesMiniList miniList)
		{
			m_Detail = View;
			m_MiniList = miniList;
		}

		public void LoadPage()
		{
			int id = Utilities.ParamUtility.GetQueryStringValue("id", -1);
			if (id != -1)
			{
				ArticlesRules.GetArticleDetialsById(id);
				AritcleDS.ArticlesDetailDataTable table = ArticlesRules.GetArticleDetialsById(id);
				if (table.Rows.Count == 1)
				{
					AritcleDS.ArticlesDetailRow row = table[0];
					if (row != null)
					{
						m_Detail.Title = row.Title;
						m_Detail.Tags = row.Tags;
						m_Detail.Content = row.Content;
						m_Detail.LastUpdateDate = row.LastUpdateDate;
						m_Detail.Author = row.AuthorName;
						m_Detail.CategoryName = row.CategoryName;
						m_Detail.CategoryId = row.CategoryId;
						m_Detail.AuthorId = row.UserId;
						m_Detail.ArticleId = row.ArticleId;


						CheckEditable(row);

						m_HtmlHeader = new HtmlHeaderInfo
									{
										Title = row.Title,
										Description = row.Summary,
										Keywords = row.Tags
									};
					}
				}

				ArticlesRules.IncreaseArticles(id);
			}

			m_MiniList.Articles = ArticlesRules.GetFavorArticles();
		}

		private void CheckEditable(AritcleDS.ArticlesDetailRow row)
		{
			m_Detail.IsEditable = false;
			Permissions currentPermission = UsersUtility.GetCurrentUserRole();
			switch (currentPermission)
			{
				case Permissions.Author:
					Guid? userId = UsersUtility.GetCurrentUserId();
					if (userId.HasValue && row.UserId == userId.Value)
					{
						m_Detail.IsEditable = true;
					}
					break;
				case Permissions.Admin:
					m_Detail.IsEditable = true;
					break;
				default:
					m_Detail.IsEditable = false;
					break;
			}
		}

		public HtmlHeaderInfo GetHeaderInfo()
		{
			return m_HtmlHeader ?? new HtmlHeaderInfo();
		}
	}
}